#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：tool.py
@Author  ：平
@Date    ：2025/10/1 21:22 
"""
import aiohttp
from langchain_core.tools import tool
from typing import Literal
import logging
from app.config.config import settings
from app.repositry.book_repo import query_by_mix_book
from app.vector.vector import vectorstore

logger = logging.getLogger(__name__)


@tool
def handler_to_retrieval(intention: str):
    """
    将执行权交给检索智能体以完成复杂任务
    Args:
        intention: 用户意图
    """
    pass


@tool
def rag_retrieval(query: str, k: int = 10, search_type: Literal["hybrid", "vector", "bm25"] = "hybrid") -> list[dict]:
    """该工具是知识库检索工具，主要用于实现RAG智能检索。

    Args:
        query: 检索内容
        k: 检索数量，默认：10
        search_type: 搜索类型（hybrid、vector、bm25）

    Returns: 检索出的文档，(content:文档正文、metadata:文档元数据、score:文档得分)

    """
    logger.info(f"工具:rag_retrieval内容:{query},数量:{k},类型:{search_type}")
    return [{"content": doc.page_content, "metadata": doc.metadata, "score": score} for doc, score in
            vectorstore.search(query, k, search_type) if score > 0.6]


@tool
async def web_search(query: str):
    """
    通过谷歌搜索获取结果，建议与web_page工具结合使用获取网页内容
    Args:
        query: 搜索内容
    Returns: 搜索结果列表
    """
    logger.info(f"工具:web_search,内容:{query}")
    async with aiohttp.ClientSession() as session:
        payload = {
            "q": query,
            "gl": "cn",
            "hl": "zh-cn"
        }
        headers = {
            'X-API-KEY': settings.SERPER_API_KEY,
        }
        async with session.post(settings.SERPER_SEARCH_URL, json=payload, headers=headers) as response:
            response.raise_for_status()
            return await response.json()


@tool
async def web_page(url: str):
    """
    通过url获取网页内容
    Args:
        url: 网页url
    Returns: 网页内容
    """
    logger.info(f"工具:web_page,网页url:{url}")
    async with aiohttp.ClientSession() as session:
        payload = {
            "url": url
        }
        headers = {
            'X-API-KEY': settings.SERPER_API_KEY,
        }
        async with session.post(settings.SERPER_WEBPAGE_URL, json=payload, headers=headers) as response:
            response.raise_for_status()
            return await response.json()


@tool
def query_book(id:int=None,title:str=None):
    """
    获取知识库的书籍列表，在查询全部书籍信息时不需要任何参数
    Args:
        id: 书籍id(可选)，用于精确获取某个书籍信息
        title: 书籍名称(可选)，用于模糊获取书籍信息

    Returns: 知识库的书籍列表

    """
    logger.info(f"工具:query_book,id:{id},title:{title}")
    return [book.to_dict() for book in query_by_mix_book(id,title)]
